<template>
  <div>
    <el-card class="sur-card">
      <el-row>
        <div class="search-section">
          <el-form :inline="true">
            <el-form-item>
              <el-select
                size="small"
                v-model="pageVo.editable"
                @change="loadSampleList"
                style="width: 140px;"
              >
                <el-option value="0" label="普通样本"></el-option>
                <el-option value="1" label="蒙层样本"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button size="small" icon="el-icon-search" @click="onSearch"
                  >查询</el-button
                >
                <el-button
                  size="small"
                  icon="el-icon-refresh"
                  @click="onClearSearchForm"
                  >刷新</el-button
                >
              </el-button-group>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="danger" @click="showAddRowDialog"
                >添加样本</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-row>
      <el-tabs v-model="activeStyleId" type="card" @tab-click="onTabClick">
        <el-tab-pane
          :label="tab.name"
          :name="tab.id"
          v-for="tab in styleList"
          :key="tab.id"
        >
        </el-tab-pane>
      </el-tabs>
      <div class="list-group">
        <draggable style="width: 100%" @update="dragEnd" :key="sortChanged">
          <div
            class="list-group-item"
            v-for="sample in sampleList"
            :key="sample.id"
          >
            <div style="position: relative;">
              <el-image
                :src="sample.presetImg"
                fit="cover"
                class="image-item"
                :preview-src-list="Array.of(sample.presetImg)"
              >
              </el-image>
              <div class="hover-mask">
                <el-button
                  type="text"
                  v-if="pageVo.editable == 1"
                  @click="onSetHoles(sample)"
                  >编辑</el-button
                >
                <el-button type="text" @click="onDeleteRow(sample)"
                  >删除</el-button
                >
              </div>
            </div>
          </div>
        </draggable>
      </div>
      <el-row>
        <el-pagination
          class="page-section"
          background
          @current-change="onPaging"
          :page-size="pageVo.size"
          @size-change="handleSizeChange"
          :page-sizes="[20, 50, 100, 200]"
          layout="total,sizes,prev, pager, next"
          :total="pageVo.total"
        />
      </el-row>
    </el-card>
    <!--    编辑坑位-->
    <el-dialog title="编辑坑位" :visible.sync="editHoleVisible" width="70%">
      <el-form
        :model="mbCaseSampleModel"
        label-position="left"
        label-width="120px"
      >
        <el-row style="display: flex;overflow: auto;">
          <div
            style="margin-right: 20px;"
            v-for="(hole, index) in mbCaseSampleModel.holes"
            :key="index"
          >
            <el-divider>第{{ index + 1 }}个坑位</el-divider>
            <el-form-item label="坑类型">
              <el-switch v-model="hole.isTransparent"></el-switch>
            </el-form-item>
            <el-form-item label="填充类型">
              <el-select v-model="hole.fillType">
                <el-option label="原图" value="intact"></el-option>
                <el-option label="人体" value="body"></el-option>
                <el-option label="头部" value="header"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="填充位置">
              <el-select v-model="hole.fillLayer">
                <el-option label="预置图下层" value="under"></el-option>
                <el-option label="预置图上层" value="upper"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="左边距">
              <el-input-number
                v-model="hole.marginLeft"
                precision="2"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="上边距">
              <el-input-number
                v-model="hole.marginTop"
                precision="2"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="坑宽度">
              <el-input-number
                v-model="hole.width"
                precision="2"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="坑高度">
              <el-input-number
                v-model="hole.height"
                precision="2"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="角度">
              <el-input-number
                v-model="hole.angle"
                precision="2"
              ></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="danger" @click="onDeleteHole(index)"
                >删除坑位</el-button
              >
            </el-form-item>
          </div>
        </el-row>
        <el-button
          size="small"
          style="width: 280px;"
          type="primary"
          @click="onAddHole"
          >添加坑位</el-button
        >
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editHoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSaveHoles">保存</el-button>
      </span>
    </el-dialog>
    <!--    编辑row对话框-->
    <el-dialog title="编辑样本" :visible.sync="editRowVisible">
      <el-form
        :model="mbCaseSampleModel"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="样本图">
          <el-upload
            style="display: inline-block;"
            :http-request="handlePresetImgUploadFile"
            multiple
            :show-file-list="false"
          >
            <el-button size="small" type="primary" icon="el-icon-picture"
              >点击上传</el-button
            >
          </el-upload>
          <el-avatar
            style="margin-top: 10px;height: 100px;width: 100px;display: flex;justify-content: center;"
            v-if="mbCaseSampleModel.presetImg"
            shape="square"
            size="100"
            fit="contain"
            :src="mbCaseSampleModel.presetImg"
          ></el-avatar>
        </el-form-item>
        <!-- <el-form-item label="是否可编辑">
          <el-switch
            v-model="mbCaseSampleModel.editable"
            :inactive-value="0"
            :active-value="1"
          ></el-switch>
        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRowVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSaveRow">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMbCaseSample,
  getMbCaseSampleByPage,
  getSampleHoles,
  removeMbCaseSampleById,
  saveSampleHoles,
  switchSort,
  updateMbCaseSampleById
} from "@/api/admin-api/MbCaseSampleApi";
import { getSampleStyleByPage } from "@/api/admin-api/SampleStyleApi";
import {
  getUploadItemMediaToken,
  uploadFileToAliOss
} from "@/api/admin-api/FileApi";
import draggable from "vuedraggable";

export default {
  name: "MbCaseSample",
  components: {
    draggable
  },
  data() {
    return {
      activeStyleId: "",
      sortChanged: false,
      pageVo: {
        current: 1,
        size: 20,
        total: 0, //总数量
        pages: 0, //总页数
        orders: [{ column: "sort" }], //排序字段
        editable: "0",
        styleId: ""
      },
      editRowVisible: false,
      editHoleVisible: false,
      mbCaseSampleModel: {
        id: null,
        styleId: null,
        presetImg: null,
        editable: null,
        sort: null,
        holes: []
      },
      loadingTable: false,
      sampleList: [],
      styleList: [] //风格列表
    };
  },
  methods: {
    onSaveHoles() {
      saveSampleHoles(
        this.mbCaseSampleModel.id,
        this.mbCaseSampleModel.holes
      ).then(() => {
        this.$message.success("保存成功");
        this.editHoleVisible = false;
      });
    },
    onDeleteHole(index) {
      this.mbCaseSampleModel.holes.splice(index, 1);
    },
    onAddHole() {
      // this.mbCaseSampleModel.holes = [];
      if (this.mbCaseSampleModel.holes === undefined) {
        this.$set(this.mbCaseSampleModel, "holes", []);
      }
      this.mbCaseSampleModel.holes.push({
        isTransparent: true,
        fillType: "intact",
        fillLayer: "upper",
        marginLeft: 0,
        marginTop: 0,
        width: 100,
        height: 100,
        angle: 0
      });
    },
    dragEnd(evt) {
      switchSort(
        this.sampleList[evt.oldIndex].id,
        this.sampleList[evt.newIndex].id
      )
        .then(() => {
          this.$message.success("顺序更换成功");
          this.loadSampleList();
          this.sortChanged = !this.sortChanged;
        })
        .catch(() => {});
    },

    handlePresetImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            this.mbCaseSampleModel.presetImg =
              "https://asset.fanghaowu.com/" + fileKey;
            this.onSaveRow();
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    async loadStyleList() {
      return new Promise(resolve => {
        getSampleStyleByPage({
          size: 100,
          type: "DIY_MOBILE_CASE",
          orders: [{ column: "sort" }]
        }).then(data => {
          resolve(data.records);
        });
      });
    },
    onSearch() {
      this.loadSampleList();
    },
    onClearSearchForm() {
      this.pageVo = this.$options.data().pageVo;
      this.loadSampleList();
    },
    onTabClick(tab) {
      // this.pageVo.editable = tab.name;
      this.loadSampleList();
      console.log("tab", tab.name);
      this.mbCaseSampleModel.styleName = tab.label;
      this.mbCaseSampleModel.styleId = tab.name;
    },
    onPaging(currentPage) {
      // 页码改变
      this.pageVo.current = currentPage;
      this.loadSampleList();
    },
    handleSizeChange(val) {
      //页大小改变
      this.pageVo.size = val;
      this.loadSampleList();
    },
    onSaveRow() {
      //保存或更新
      if (this.mbCaseSampleModel.id) {
        //更新
        this.$loading();
        updateMbCaseSampleById(this.mbCaseSampleModel)
          .then(() => {
            this.$message.success("操作成功");
            this.loadSampleList();
            this.$loading().close();
            this.editRowVisible = false;
          })
          .catch(() => {
            this.$loading().close();
          });
      } else {
        //保存
        this.$loading();
        addMbCaseSample(this.mbCaseSampleModel)
          .then(() => {
            this.$message.success("操作成功");
            this.$loading().close();
            this.loadSampleList();
            // this.editRowVisible = false;
          })
          .catch(() => {
            this.$loading().close();
          });
      }
    },
    showAddRowDialog() {
      //显示添加行对话框
      this.editRowVisible = true;
      this.mbCaseSampleModel = this.$options.data().mbCaseSampleModel;
      this.mbCaseSampleModel.styleId = this.activeStyleId;
      this.mbCaseSampleModel.editable = this.pageVo.editable;
      // this.mbCaseSampleModel.editable = 0;
    },
    loadSampleList() {
      this.loadingTable = true;
      this.pageVo.styleId = this.activeStyleId;
      getMbCaseSampleByPage(this.pageVo)
        .then(data => {
          this.sampleList = data.records;
          this.pageVo.current = data.current;
          this.pageVo.pages = data.pages;
          this.pageVo.total = Number(data.total);
          this.loadingTable = false;
        })
        .catch(() => {
          this.loadingTable = false;
        });
    },
    onSetHoles(row) {
      this.mbCaseSampleModel = row;
      getSampleHoles(row.id).then(holes => {
        this.$set(this.mbCaseSampleModel, "holes", holes);
        this.editHoleVisible = true;
      });
    },
    onEditRow(row) {
      //编辑行
      this.mbCaseSampleModel = row;
      this.editRowVisible = true;
    },
    onDeleteRow(row) {
      //删除行
      this.$confirm("确定要删除当前行吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(() => {
        this.$loading();
        removeMbCaseSampleById(row.id)
          .then(() => {
            this.loadSampleList();
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    }
  },
  async mounted() {
    this.styleList = await this.loadStyleList();
    this.activeStyleId = this.styleList[0].id;
    this.loadSampleList();
  }
};
</script>
<style scoped>
.list-group {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.list-group-item {
  margin-left: 15px;
  margin-bottom: 15px;
  display: inline-block;
}
.image-item {
  width: 120px;
  height: 220px;
  border-radius: 8px;
}
.hover-mask {
  text-align: center;
  /*position: absolute;*/
  /*background-color: #42b983;*/
}
</style>
